package com.nobody.facepk.persist.type;

import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;

import org.hibernate.HibernateException;
import org.hibernate.usertype.ParameterizedType;

import com.google.gson.Gson;


public class JsonType implements org.hibernate.usertype.UserType, ParameterizedType{
	
	private Class<?> clazz;
	
	@Override
	public void setParameterValues(Properties parameters) {
		String className = parameters.getProperty("class");
		try {
			this.clazz = Class.forName(className);
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(),e);
		}
	}
	
	public int[] sqlTypes() {
		return new int[]{Types.CHAR};
	}

	public Class returnedClass() {
		return this.clazz;
	}

	public boolean equals(Object x, Object y) throws HibernateException {
		return ( x == y ) || ( x != null && x.equals( y ) );
	}

	public int hashCode(Object x) throws HibernateException {
		return x.hashCode();
	}

	public Object nullSafeGet(ResultSet rs, String[] names, Object owner) throws HibernateException, SQLException {
		String value = rs.getString(names[0]);
		if(value==null || value.isEmpty()) {
			try {
				return this.clazz.newInstance();
			} catch (Exception e) {
			}
		}
		
		Gson gson = new Gson();
		return gson.fromJson(value, this.clazz);
	}

	public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
		if ( value != null ) {
			String json = new Gson().toJson(value);
			st.setString(index,json);
		}
		else {
			st.setNull( index, sqlTypes()[0] );
		}
	}

	public Object deepCopy(Object value) throws HibernateException {
		if(value==null) return null;
		return value;
	}

	public boolean isMutable() {
		return false;
	}

	public Serializable disassemble(Object value) throws HibernateException {
		return (Serializable) value;
	}

	public Object assemble(Serializable cached, Object owner) throws HibernateException {
		return cached;
	}

	public Object replace(Object original, Object target, Object owner) throws HibernateException {
		return original;
	}
}
